const jwt = require('jsonwebtoken');
module.exports = () => {
    return async (ctx,next) => {
        console.log(ctx.get('token'));
        //不需要检查  登录  注册接口不需要检查

        let writePath = ['/api/login','/api/registry'];
        if(!writePath.includes(ctx.path)){
            //校验token
            let token = ctx.get('token');

            try{    
                jwt.verify(token,'lixd');
                await next();
            }catch(e){
                if(e.name === 'JsonWebTokenError'  || e.name === 'TokenExpiredError'){
                    //状态码  HTTP401错误代表用户没有访问权限，需要进行身份认证
                    ctx.status = 401;
                    ctx.body = {
                        code:4,
                        msg:e
                    }
                }else{
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            await next()
        }
    }
}